﻿using System;
using System.Collections.Generic;
using System.Dynamic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using NLog;
using OpenQA.Selenium.Chrome;

namespace Cbs.Lucky.WebDriverDemo
{
    class Program
    {
        private static Logger Logger = LogManager.GetCurrentClassLogger();
        static async Task Main(string[] args)
        {
            var mainJsScript = File.ReadAllText("scripts/main.js");
            var options = new ChromeOptions();
            //options.AddArgument("--incognito");
            //options.AddArgument("headless");
            //options.AddArgument("disable-infobars");
            using (var driver = new ChromeDriver(AppDomain.CurrentDomain.BaseDirectory, options))
            {
                driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(1);
                driver.Navigate().GoToUrl("https://chart.ydniu.com/trend/syx5sd/");
                await Task.Delay(1000);
                var btnQi200 = driver.FindElementByCssSelector("#filters > a:nth-child(3)");
                btnQi200.Click();
                await Task.Delay(2000);
                var testData = "2,3,4,5,8";
                var testArrStr = string.Join(",", testData
                    .Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries)
                    .Select(s => s.PadLeft(2, '0'))
                    .Select(s => $"'{s}'"));
                dynamic jsResult = driver.ExecuteScript($@"{mainJsScript};
var data = parseData();
return {{
    Data : data,
    Result : find2(data,[{testArrStr}])
}};");
                var data = jsResult["Data"];
                var result = jsResult["Result"];
                //Logger.Debug($"JSResult:{JsonConvert.SerializeObject(jsResult)}");
                //Logger.Debug($"Data:{JsonConvert.SerializeObject(data)}");
                //Logger.Debug($"Result:{JsonConvert.SerializeObject(result)}");
                IReadOnlyCollection<dynamic> ds = data;
                var ordered = ds
                    .OrderByDescending(o => o[0])
                    .Select(s => new
                    {
                        Title = s[0],
                        Data = $"{s[1]},{s[2]},{s[3]},{s[4]},{s[5]}"
                    })
                    .ToList();
                Logger.Debug($"Ordered:{JsonConvert.SerializeObject(ordered)}");
                IReadOnlyCollection<dynamic> rs = result;

                var orderResult = new List<dynamic>();
                rs.ForEach(rse =>
                {
                    var d = rse["data"];
                    var t = rse["title"];
                    var counter = 0;
                    foreach (var e in ordered)
                    {
                        if (e.Title == t)
                        {
                            break;
                        }
                        counter++;
                    }
                    orderResult.Add(new
                    {
                        Data = d,
                        Title = t,
                        Counter = counter,
                        Msg = $"遗漏 {counter} 期 , 上次是 {t} 期"
                    });
                });
                Logger.Debug($"OrderResult:{JsonConvert.SerializeObject(orderResult)}");
                var ods = orderResult
                    .OrderByDescending(o => o.Counter)
                    .ToList();
                Logger.Debug($"OrderResult重新排名:{JsonConvert.SerializeObject(ods, Formatting.Indented)}");
                driver.Close();
                await Task.Delay(1000);
            }
        }
    }
}
